package com.nowcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.RedisKeyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "登录注册控制器")
@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    // Producer:接口； kaptchaProducer:方法/Bean名称
    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    // 项目路径
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @ApiOperation("请求转发到注册页面")
    @GetMapping("/register")
    public String getRegisterPage() {
        return "/site/register";
    }

    @ApiOperation("登录")
    @GetMapping("/login")
    public String getLoginPage() {
        return "/site/login";
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        // 清理授权
        SecurityContextHolder.clearContext();
        // 转发去登录  redirect是GET请求
        return "redirect:/login";
    }

    @ApiOperation("注册并发送激活邮件")
    @PostMapping("/register")
    public String register(Model model, User user, String confirmPassword) {
        // 方法调用前,springMVC的dispatchServlet会自动实例化user
        // confirmpassword从request里可以取到，用param即可
        Map<String, Object> map = userService.register(user, confirmPassword);
        if (map != null && map.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        }

        model.addAttribute("usernameMsg", map.get("usernameMsg"));
        model.addAttribute("passwordMsg", map.get("passwordMsg"));
        model.addAttribute("emailMsg", map.get("emailMsg"));
        return "/site/register";
    }

    @ApiOperation("处理激活邮件请求")
    // http//:localhost:8080/community/activation/id/code
    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int result = userService.activation(userId, code);
        if (result == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功，您的账号已经可以正常使用了");
            model.addAttribute("target", "/login");
        } else if (result == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效操作，该账号已激活");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败，您的提供的激活码错误");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }

    // 获取验证码的方法
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        // 生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);
        // 将验证码存到session
        // session.setAttribute("kaptcha", text);

        // 验证码的归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        // cookie -> key:value
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        // 60s过期
        cookie.setMaxAge(60);
        // 有效路径
        cookie.setPath(contextPath);
        response.addCookie(cookie);

        // 将验证码存到redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        // redisKey -> 验证码文本
        redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS);

        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            // 输出(图片文件对象，格式，使用的流)
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            logger.error("响应验证码失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param code       : 校验码
     * @param rememberme : 记住我
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public String login(String username, String password, String code, boolean rememberme,
                        Model model, /*HttpSession session,*/ HttpServletResponse response,
                        @CookieValue("kaptchaOwner") String kaptchaOwner) {
        // code从表单获取直接注入
        // 检查验证码
        // String kaptcha = (String) session.getAttribute("kaptcha");

        // kaptchaOwner是一个零时身份凭证
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)){
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }

        // 如果kaptchaOwner过期，失效，错误
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确!");
            return "/site/login";
        }

        // 检查账号密码(记住我:默认设置)
        int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            // 设置cookie的有效时间
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            // 请求转发，一次请求
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }
}
